<?php

namespace App\Http\Controllers\CRM;

use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\CRM\CategoryRequest;
use App\Http\Resources\CRM\CategoryResource;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function create(CategoryRequest $request)
    {
        $category = Category::create($request->only(['name', 'sort']));

        return new CategoryResource($category);
    }

    public function edit(Category $category, CategoryRequest $request)
    {
        $category->update($request->only(['name', 'sort']));

        return new CategoryResource($category);
    }

    public function remove(Category $category)
    {
        if ($category->goods()->count() > 0)
            return ApiResponseHelper::json([], 400, '该分类下有商品，无法删除');

        $category->delete();

        return response()->noContent();
    }

    public function getList(Request $request)
    {
        $storeId = $request->store_id;

        $categories = Category::oldest("sort")->with("goods")->with([
            'goods.stocks' => function ($query) use($storeId) {
                $query->where("store_id", $storeId);
            }
        ])->paginate();

        return CategoryResource::collection($categories);
    }

    public function getInfo(Category $category)
    {
        $category->goods;

        return new CategoryResource($category);
    }
}
